<?php

    class AjaxController extends Zend_Controller_Action
    {

        private $_params;
        private $messageModel;
        private $commonModel;
        private $user;

        public function init()
        {
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();
            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            if (!empty($y))
                $this->user_id = $x->read()->user_id;
            $this->user = (array) $y;
//            $ajaxContext = $this->_helper->getHelper('AjaxContext');
//            $ajaxContext->addActionContext('login', 'html')
//                    ->addActionContext('register', 'html')
//                    ->addActionContext('forgotpassword', 'html')
//                    ->addActionContext('replymessage', 'json')
//                    ->initContext();
            /* Initialize action controller here */

            $this->messageModel = new Application_Model_Message;
            $this->commonModel = new Application_Model_Common;
        }

        public function bookmarkeventAction()
        {
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $model = new Application_Model_Common();
                $event_id = getEncryptedString($arr["event_id"], "decode");

                $whereCond = "eb_event_id = $event_id AND eb_user_id = " . $this->user_id;

                $is_exists = $model->is_exists(TABLE_EVENT_BOOKMARK, $whereCond);
                if (empty($is_exists))
                {
                    $data_array = array(
                        "eb_event_id" => $event_id,
                        "eb_user_id" => $this->user_id,
                        "from_ipaddress" => $_SERVER["REMOTE_ADDR"]
                    );
                    $model->insertRecordData($data_array, TABLE_EVENT_BOOKMARK);
                }
                else
                {
                    $model->deleteRecord($whereCond, TABLE_EVENT_BOOKMARK);
                }
                echo '1';
            }
            die;
        }

        function removeeventimageAction()
        {
            $file = $this->_getParam("file");
            $user_id = $this->_getParam("user_id");

            if ($user_id && $file)
            {
                $temp_url = "resources/temp/$user_id/$file";
                @unlink($temp_url);

                $msg = array();
                $msg['success'] = true;
                $msg['error'] = false;
            }
            else if ($this->_getParam("url") && $this->_getParam("id"))
            {
                @unlink($this->_getParam("url"));

                $msg = array();
                $msg['success'] = true;
                $msg['error'] = false;
            }
            else
            {
                $msg['error'] = true;
                $msg['success'] = false;
                $msg['message'] = 'Oops! Some error occurred';
            }
            echo json_encode($msg);
        }

        public function getajaxeventchatAction()
        {
            $model = new Application_Model_Common();
            $arr = $this->getRequest()->getPost();
            $last_event_id = $arr["last_event_id"];
            $event_id = getEncryptedString($arr["event_id"], "decode");
//            echo $arr["event_id"]."<br>";
//            echo $event_id; die;
            $whereCond = "ec.ec_event_id = $event_id";

            if (!empty($last_event_id))
                $whereCond = "ec.ec_event_id = $event_id and ec.ec_id > $last_event_id";

            $event_chat_records = $model->getAllRecordFromInnerJoin(array("ec" => TABLE_EVENT_CHAT), array("u" => TABLE_USERS), "u.user_id=ec.ec_user_id", $whereCond, "ec.ec_event_id DESC", "15");

            $chat_li = "";
            $chatUserArr = array();

            foreach ($event_chat_records as $e_key => $e_value)
            {
                $chatUserArr[] = $e_value['user_id'];
                $chat_li .= '<li>
                        <a href="#show-profile-' . $e_value['user_id'] . '" class="show-profile-test">
                            <img class="fl" src="' . getUserImage($e_value["user_id"]) . '" alt="' . $e_value["user_first_name"] . " " . $e_value["user_last_name"] . '" />
                        </a>    
                        <div class="content fl">
                            <p class="name"><span class="blu"><a href="#" class="link_to_click" data-path="$(this).parent().parent().parent().prev();"><strong>' . $e_value["user_first_name"] . " " . $e_value["user_last_name"] . '</strong></a></span>, <span class="time">' . getTimeAgo(strtotime($e_value["ec_timestamp"])) . '</span></p>
                            <p>' . $e_value["ec_message"] . '</p>
                        </div>
                        <div class="cf"></div>
                    </li>';
            }

            $last_event_id = "";
            if (!empty($event_chat_records))
            {
                $array_length = count($event_chat_records);
                $last_event_id = $event_chat_records[$array_length - 1]["ec_id"];
            }

            $send_Array = array("chat" => $chat_li, "last_event_id" => $last_event_id, "chatPopup" => $this->view->getHelper('Event')->getChatPopup($chatUserArr, false));
            echo json_encode($send_Array);
            die;
        }

        public function eventchatsaveAction()
        {
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $model = new Application_Model_Common();

                $event_id = getEncryptedString(trim($arr["event_id"]), "decode");
                $user_id = getEncryptedString(trim($arr["user_id"]), "decode");
                $message = addslashes(trim($arr["message"]));

                $data_array = array(
                    "ec_event_id" => $event_id,
                    "ec_user_id" => $user_id,
                    "ec_message" => $message,
                    "from_ipaddress" => $_SERVER["REMOTE_ADDR"],
                );
                $model->insertRecordData($data_array, TABLE_EVENT_CHAT);
                $last_inserted_id = $model->getLastInsertId(TABLE_EVENT_CHAT);
                $user_record = $model->getdata(TABLE_USERS, "user_id = $user_id");
                $user_full_name = $user_record["user_first_name"] . " " . $user_record["user_last_name"];

                $chat_li = '<li>
                        <img class="fl" src="' . getUserImage($user_id) . '" alt="' . $user_full_name . '" />
                        <div class="content fl">
                            <p class="name"><span class="blu"><strong>' . $user_full_name . '</strong></span>, <span class="time">' . getTimeAgo(time()) . '</span></p>
                            <p>' . $message . '</p>
                        </div>
                        <div class="cf"></div>
                    </li>';

                $send_Array = array("chat" => $chat_li, "last_event_id" => $last_inserted_id);
                echo json_encode($send_Array);
            }
            die;
        }

        public function geteventdistanceAction()
        {
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $another_address = $arr["another_address"];
                $event_address = $arr["event_address"];

                $distance = getEventDistanceAway($event_address, $another_address);
                if ($distance == "NA")
                    echo $distance;
                else
                    echo $distance . " Miles";
            }
            die;
        }

        public function outboxAction()
        {


            $commonModel = new Application_Model_Common();
            $friend_records = $commonModel->getAllRecordFromInnerJoin(TABLE_FRIEND_REQUESTS, 'users', 'users.user_id = friend_requests.user_sent_to', 'user_sent_from=' . $this->user['user_id'] . ' and user_active="1"');
            foreach ($friend_records as $frndKey => $frndValue)
            {
                $friendArr[] = $frndValue['user_id'];
            }

            //users created friend group
            $groupArr = $commonModel->getAllRecordDetail(TABLE_FRIEND_GROUPS, 'created_by= "' . $this->user['user_id'] . '"', 'group_name asc');
            $key = count($groupArr);
            $groupArr[$key]['group_id'] = '0';
            $groupArr[$key]['group_name'] = 'others';
            $groupArr[$key]['group_name'] = 'others';


            $user_id = $this->user['user_id'];
            $page = $this->_getParam('page', 1);
            if (!$user_id)
            {
                echo json_encode(array("error" => true));
                die;
            }
            $sentMsgArr = $this->messageModel->getUserMessages($this->user['user_id'], false, true)->limitPage($page, 10)->query()->fetchAll();

            foreach ($sentMsgArr as $mKey => $mValue)
            {

                $mustacheData['messages'][$mKey]['message_id'] = $mValue['message_id'];
                $mustacheData['messages'][$mKey]['message'] = $mValue['message_content'];
                $mustacheData['messages'][$mKey]['time'] = getTimeAgo($mValue['message_timestamp']);
                $mustacheData['messages'][$mKey]['name'] = $mValue['user_username'];
                $mustacheData['messages'][$mKey]['receiver_id'] = $mValue['message_to'];
                $mustacheData['messages'][$mKey]['user_id'] = $this->user['user_id'];
                $mustacheData['messages'][$mKey]['is_inbox'] = false;
                $mustacheData['messages'][$mKey]['read'] = $mValue['message_read'] ? 'white-bg' : '';
                $mustacheData['messages'][$mKey]['delete-link'] = $this->view->baseUrl() . "/ajax/deletemessage/id/" . $mValue['message_id'] . "/outbox/1";
                $mustacheData['messages'][$mKey]['avatar'] = is_file(ROOT_PATH . "/" . MEMBER_IMAGE_PATH . "/" . $mValue['user_id'] . ".jpg") ? $this->view->baseUrl(MEMBER_IMAGE_PATH . "/" . $mValue['user_id'] . ".jpg") : $this->view->baseUrl(MEMBER_NO_IMAGE_FILE);
                $mustacheData['messages'][$mKey]['notadmin'] = $mValue['message_from'] == '0' ? false : true;
                //new
                $mustacheData['messages'][$mKey]['user_bio'] = $mValue['user_bio'];
                $mustacheData['messages'][$mKey]['friend_name'] = $mValue['user_first_name'] . " " . $mValue['user_last_name'];
                $mustacheData['messages'][$mKey]['dob'] = date("d F Y", strtotime($mValue['user_dob']));
                $mustacheData['messages'][$mKey]['user_from'] = $mValue['user_city'];
                $mustacheData['messages'][$mKey]['facebook_url'] = getFacebookUsernameUrl($mValue['facebook_username']);
                $mustacheData['messages'][$mKey]['twitter_url'] = getTwitterUsernameUrl($mValue['twitter_username']);
                $mustacheData['messages'][$mKey]['linkedin_url'] = getLinkedinUsernameUrl($mValue['linkedin_username']);
                $mustacheData['messages'][$mKey]['encrypted_user_id'] = getEncryptedString($mValue['message_to']);
                $mustacheData['messages'][$mKey]['add_friend_txt'] = !in_array($friend_id, $friendArr) ? "Add as Friend" : "Add to another group";
                $ugroupArr = $this->view->getHelper('Profile')->getFriendGroup($this->user['user_id'], $mValue['message_to']);

                foreach ($groupArr as $gKey => $gValue)
                {
                    if (in_array_custom($gValue['group_id'], $ugroupArr, 'group_id'))
                        continue;
                    $mustacheData['messages'][$mKey]['group'][$gKey]['group_id'] = $gValue['group_id'];
                    $mustacheData['messages'][$mKey]['group'][$gKey]['group_name'] = $gValue['group_name'];
                    $mustacheData['messages'][$mKey]['group'][$gKey]['total_group_members'] = $this->view->getHelper('Profile')->getGroupMembersCount($this->user['user_id'], $gValue['group_id']);
                }
            }
            $mustacheData['error'] = false;
            $mustacheData['outboxCount'] = @count($mustacheData['messages']);

            echo!empty($mustacheData['messages']) ? json_encode($mustacheData) : json_encode(array('nomessage' => true));
        }

        function inboxAction()
        {

            $commonModel = new Application_Model_Common();
            $friend_records = $commonModel->getAllRecordFromInnerJoin(TABLE_FRIEND_REQUESTS, 'users', 'users.user_id = friend_requests.user_sent_to', 'user_sent_from=' . $this->user['user_id'] . ' and user_active="1"');
            foreach ($friend_records as $frndKey => $frndValue)
            {
                $friendArr[] = $frndValue['user_id'];
            }

            //users created friend group
            $groupArr = $commonModel->getAllRecordDetail(TABLE_FRIEND_GROUPS, 'created_by= "' . $this->user['user_id'] . '"', 'group_name asc');
            $key = count($groupArr);
            $groupArr[$key]['group_id'] = '0';
            $groupArr[$key]['group_name'] = 'others';
            $groupArr[$key]['group_name'] = 'others';


            $user_id = $this->user['user_id'];
            $page = $this->_getParam('page', 1);
            if (!$user_id)
            {
                echo json_encode(array("error" => true));
                die;
            }

            $msgArr = $this->messageModel->getUserMessages($this->user['user_id'], true, true)->limitPage($page, 10)->query()->fetchAll();

            foreach ($msgArr as $mKey => $mValue)
            {

                $mustacheData['messages'][$mKey]['message_id'] = $mValue['message_id'];
                $mustacheData['messages'][$mKey]['message'] = $mValue['message_content'];
                $mustacheData['messages'][$mKey]['time'] = getTimeAgo($mValue['message_timestamp']);
                $mustacheData['messages'][$mKey]['name'] = $mValue['user_username'];
                $mustacheData['messages'][$mKey]['receiver_id'] = $mValue['message_from'];
                $mustacheData['messages'][$mKey]['user_id'] = $this->user['user_id'];
                $mustacheData['messages'][$mKey]['is_inbox'] = true;
                $mustacheData['messages'][$mKey]['read'] = $mValue['message_read'] ? 'white-bg' : '';
                $mustacheData['messages'][$mKey]['delete-link'] = $this->view->baseUrl() . "/ajax/deletemessage/id/" . $mValue['message_id'] . "/inbox/1";
                $mustacheData['messages'][$mKey]['avatar'] = is_file(ROOT_PATH . "/" . MEMBER_IMAGE_PATH . "/" . $mValue['user_id'] . ".jpg") ? $this->view->baseUrl(MEMBER_IMAGE_PATH . "/" . $mValue['user_id'] . ".jpg") : $this->view->baseUrl(MEMBER_NO_IMAGE_FILE);
                $mustacheData['messages'][$mKey]['notadmin'] = $mValue['message_from'] == '0' ? false : true;
                //new
                $mustacheData['messages'][$mKey]['user_bio'] = $mValue['user_bio'];
                $mustacheData['messages'][$mKey]['friend_name'] = $mValue['user_first_name'] . " " . $mValue['user_last_name'];
                $mustacheData['messages'][$mKey]['dob'] = date("d F Y", strtotime($mValue['user_dob']));
                $mustacheData['messages'][$mKey]['user_from'] = $mValue['user_city'];
                $mustacheData['messages'][$mKey]['facebook_url'] = getFacebookUsernameUrl($mValue['facebook_username']);
                $mustacheData['messages'][$mKey]['twitter_url'] = getTwitterUsernameUrl($mValue['twitter_username']);
                $mustacheData['messages'][$mKey]['linkedin_url'] = getLinkedinUsernameUrl($mValue['linkedin_username']);
                $mustacheData['messages'][$mKey]['encrypted_user_id'] = getEncryptedString($mValue['message_from']);
                $mustacheData['messages'][$mKey]['add_friend_txt'] = !in_array($friend_id, $friendArr) ? "Add as Friend" : "Add to another group";
                $mustacheData['messages'][$mKey]['create_group'] = !in_array($friend_id, $friendArr) ? "Add as Friend" : "Add to another group";
                $ugroupArr = $this->view->getHelper('Profile')->getFriendGroup($this->user['user_id'], $mValue['message_from']);
                foreach ($groupArr as $gKey => $gValue)
                {
                    $mustacheData['messages'][$mKey]['group'][$gKey]['group_id'] = $gValue['group_id'];
                    $mustacheData['messages'][$mKey]['group'][$gKey]['group_name'] = $gValue['group_name'];
                    $mustacheData['messages'][$mKey]['group'][$gKey]['total_group_members'] = $this->view->getHelper('Profile')->getGroupMembersCount($this->user['user_id'], $gValue['group_id']);
                }
            }
            $mustacheData['error'] = false;
            $mustacheData['inboxCount'] = @count($mustacheData['messages']);
            echo!empty($mustacheData) ? json_encode($mustacheData) : json_encode(array('nomessage' => true));
        }

        function replymessageAction()
        {
            $msg = array();
            $params = $this->_getAllParams();
            $result = $this->messageModel->sendMessage($params['receiverId'], false, $params['msgContent']);

            if ($result > 0)
            {
                //$msgResult = $this->messageModel->getMessagebyId($result);
                $msg['success'] = true;
                $msg['id'] = $result;
                //$msg['message_content'] = $msgResult[''];
                $msg['message'] = 'Message successfully sent';
            }
            else
            {
                $msg['error'] = true;
                $msg['message'] = 'some error occurred';
            }


            echo json_encode($msg);
            //echo $msg;
        }

        function deletemessageAction()
        {

            $message_id = $this->_getParam('id');
            $is_inbox = $this->_getParam('inbox', false);

            $msg = array();
            //checking whether the user is logged in or not
            $user_id = $this->user['user_id'];
            if (!$user_id)
            {
                $msg['error'] = true;
                $msg['success'] = false;
                $msg['reason'] = 'User session time out';
                $msg['message'] = 'Oops! some error occurred';
                exit(json_encode($msg));
            }

            if (!$message_id)
            {

                $msg['error'] = true;
                $msg['success'] = false;
                $msg['reason'] = 'message_id null';
                $msg['message'] = 'Oops! some error occurred';
                exit(json_encode($msg));
            }

            if ($is_inbox)
            {
                $val_delete = $this->messageModel->validateUserMessage($user_id, $message_id, $is_inbox);
            }
            else
            {
                $val_delete = $this->messageModel->validateUserMessage($user_id, $message_id, $is_inbox);
            }

            if (!$val_delete)
            {

                $msg['error'] = true;
                $msg['success'] = false;
                $msg['reason'] = 'Have you gone nuts trying to delete messages of other users? Idiot..';
                $msg['message'] = 'Sorry! delete messages of yourself..';
                exit(json_encode($msg));
            }



            try
            {
                $result = $this->messageModel->deleteMsg($message_id, $is_inbox);
            }
            catch (Exception $e)
            {

                $msg['error'] = true;
                $msg['success'] = false;
                $msg['reason'] = $e->getMessage();
                $msg['message'] = 'Oops! some error occurred';
                exit(json_encode($msg));
            }



            $msg['error'] = false;
            $msg['success'] = true;
            $msg['message'] = 'Message successfully deleted';
            exit(json_encode($msg));
        }

        public function loginAction()
        {
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $model = new Application_Model_Common();

                $user_email = trim($arr["user_email"]);
                $user_password = trim($arr["user_password"]);

                if ($user_email == "Email Address" || empty($user_password))
                {
                    $_SESSION["messageError"] = "Please fill up all the details";
                    echo '1';
                    die;
                }

                $check_record = $model->getdata(TABLE_USERS, "user_email = '$user_email' and user_password = '" . md5($user_password) . "'");
                if (!empty($check_record))
                {
                    if ($check_record["user_active"] == "0")
                    {
                        $_SESSION["messageError"] = "Your account is not active";
                        echo '1';
                        die;
                    }
                }
                else
                {
                    $is_email_exists = $model->getdata(TABLE_USERS, "user_email = '$user_email'");
                    if (empty($is_email_exists))
                    {
                        $_SESSION["messageError"] = "No such email found";
                        echo '1';
                        die;
                    }
                    else
                    {
                        $is_password_correct = $model->getdata(TABLE_USERS, "user_email = '$user_email' and user_password = '" . md5($user_password) . "'");
                        if (empty($is_password_correct))
                        {
                            $_SESSION["messageError"] = "Invalid Password";
                            echo '1';
                            die;
                        }
                    }

//                    $_SESSION["messageError"] = "No such record found";
//                    echo '1';
//                    die;
                }

                $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

                $authAdapter->setTableName(TABLE_USERS)
                        ->setIdentityColumn('user_email')
                        ->setCredentialColumn('user_password')
                        ->setCredentialTreatment('MD5(?)');

                $authAdapter->setIdentity($user_email)
                        ->setCredential($user_password);

                $zend_auth = Zend_Auth::getInstance();
                $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
                $result = $zend_auth->authenticate($authAdapter);

                if ($result->isValid())
                {
                    $user = $authAdapter->getResultRowObject(null, 'user_password');

                    $zend_auth->getStorage()->write($user);
                }
                else
                {
                    $_SESSION["messageError"] = "Invalid Email/Password.";
                }
                echo '1';
            }
            die;
        }

        public function registerAction()
        {
            $model = new Application_Model_Common();

            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                extract($arr);

                if ($user_email == "Email Address" || $user_username == "Username" || $user_first_name == "First Name" || $user_last_name == "Last Name")
                {
                    $_SESSION["messageError"] = "Please fill up all the details";
                    echo '1';
                    die;
                }

                if (isset($arr["agree_terms"]) && $arr["agree_terms"] == "1")
                {
                    if (!empty($user_email))
                    {
                        $is_exists = $model->is_exists(TABLE_USERS, "user_email='$user_email'");
                        if (!empty($is_exists))
                        {
                            $_SESSION["messageError"] = "Email already exists";
                        }
                        else
                        {
                            $is_username_exists = $model->is_exists(TABLE_USERS, "user_username='$user_username'");
                            if (!empty($is_username_exists))
                            {
                                $_SESSION["messageError"] = "Username already exists";
                            }
                            else
                            {
                                $activation_link = getActivationKey($arr["user_email"] . time());
                                $arr["user_activation_link"] = $activation_link;
                                $arr["user_password"] = md5($arr["user_password"]);
                                unset($arr["agree_terms"]);
                                $model->insertRecordData($arr, TABLE_USERS);

                                $email_model = new Application_Model_Email ( );
                                $activation_url = SITE_HTTP_URL . "/index/activateaccount?activation_link=$activation_link";
                                $messageContent = "Welcome to " . SITE_NAME . ".<br/>Please click on the link below to activate your account.<br/>$activation_url";

                                if ($_SERVER["REMOTE_ADDR"] != "127.0.0.1")
                                    $email_model->sendMail($arr["user_email"], SITE_EMAIL, SITE_NAME, "Welcome to " . SITE_NAME, $messageContent);

                                $_SESSION["messageSuccess"] = "Please check your email";
                            }
                        }
                    }
                }
                else
                {
                    $_SESSION["messageError"] = "Please accept our terms";
                }
                echo '1';
            }
            die;
        }

        public function forgotpasswordAction()
        {
            $model = new Application_Model_Common();
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $user_email = trim($arr["user_email"]);

                $is_exists = $model->is_exists(TABLE_USERS, "user_email='$user_email'");
                if (empty($is_exists))
                {
                    $_SESSION["messageError"] = "No such record found";
                    echo '1';
                }
                else
                {
                    //  new password and send email    
                    $new_password = strtoupper(substr(md5(time()), 0, 8));

                    $email_model = new Application_Model_Email();

                    $toEmail = $user_email;
                    $fromEmail = SITE_EMAIL;
                    $fromName = SITE_NAME;
                    $subject = SITE_NAME . ' Password Reset';
                    $messageContent = "  Your new password is <strong>$new_password</strong>";

                    $sendEmail = $email_model->sendMail($toEmail, $fromEmail, $fromName, $subject, $messageContent);

                    if ($sendEmail)
                    {
                        $model->updateRecordData(array("user_password" => md5($new_password)), "user_email='$user_email'", TABLE_USERS);
                        $_SESSION["messageSuccess"] = "Your new password has been sent to your email address";
                    }
                    else
                    {
                        $_SESSION["messageError"] = "Sorry, an error occurred, please try again later.";
                    }
                    echo '1';
                }
            }
            die;
        }

        function readmessageAction()
        {
            $message_id = $this->_getParam("id");
            if (!$message_id)
            {
                exit("error occurred");
            }
            $msgArr = $this->messageModel->getMessagebyId($message_id);

            //check if the message is of inbox or outbox
            if ($msgArr['message_to'] == $this->user['user_id'])
            {
                $data['message_read'] = '1';
                $this->messageModel->update($data, "message_id = " . $message_id);
            }
            echo $msgArr['message_content'];
        }

        function eventrequestAction()
        {
            //echo "sdfds";
            //prd($this->_getParam("redirect_uri"));
            $ejId = $this->_getParam("ejId");
            $event_id = $this->_getParam("eventId");
            $respond = $this->_getParam("respond");

            $this->commonModel = new Application_Model_Common;
            $model = new Application_Model_Common;
            $msg = array();
            if ($respond == "accept")
            {
                $data = array();

                //$whereCond = "ej_id = " . $ejId;
                $getData = $model->getdata(TABLE_EVENTS, "event_id=$event_id");
                $user_id = $getData["ej_user_id"];
                $data['ej_event_id'] = $event_id;
                $data['ej_user_id'] = $this->user_id;
                $data['ej_is_accepted'] = '1';
                $data['ej_is_invited'] = '0';
                $data['from_ipaddress'] = $_SERVER["REMOTE_ADDR"];
//                $res = $this->commonModel->updateRecordData($data, $whereCond, TABLE_EVENT_JOIN);
//                prd($data);
                if(!empty($ejId))
                $model->deleteRecord("ej_id=$ejId", TABLE_EVENT_JOIN);
                $model->insertRecordData($data, TABLE_EVENT_JOIN);
                $last_id = $model->getMaxId(TABLE_EVENT_JOIN, "ej_id");

                if ($last_id)
                {
                    $where = "ej_id =" . $last_id["maxid"];

                    $result = $this->commonModel->getAdapter()->select()
                                    ->from(TABLE_EVENT_JOIN)
                                    ->join(TABLE_USERS, TABLE_USERS . '.user_id = ' . TABLE_EVENT_JOIN . '.ej_user_id')
                                    ->join(TABLE_EVENTS, TABLE_EVENTS . ".event_id = " . TABLE_EVENT_JOIN . ".ej_event_id")
                                    ->where($where)
                                 ->query()->fetchAll()
                    ;
//                    prd($result);
                  //prd($result->__toString());
//                    $result = $model->getAdapter()->query()->fetchAll();
                    //getAllRecordFromInnerJoin(TABLE_EVENT_JOIN, TABLE_USERS, TABLE_USERS . '.user_id = ' . TABLE_EVENT_JOIN . '.ej_user_id', $whereCond);
                    $msg['message'] = $result[0]['user_first_name'] . ' ' . $result[0]['user_last_name'] . " has joined your event";

                    //prd($result);
                    //status code 3 - send notification to host
                    $this->addNotification($this->user_id, 5, $result[0]['event_id'], $result[0]['user_id']);

                    //status code 5 - send notification to user
                    $this->addNotification($result[0]['user_id'], 3, $result[0]['event_id']);


                    $msg['accept'] = true;
                    $msg['reject'] = false;
                }
            }
            else
            {



                $whereCond = "ej_id = " . $ejId;

                //$result = $this->commonModel->getAllRecordFromInnerJoin('friend_requests', 'users', 'friend_requests.user_sent_from = users.user_id', $whereCond);
                //$result = $this->commonModel->getAllRecordFromInnerJoin(TABLE_EVENT_JOIN, TABLE_USERS, TABLE_USERS . '.user_id = ' . TABLE_EVENT_JOIN . '.ej_user_id', $whereCond);
                $result = $this->commonModel->getAdapter()->select()
                        ->from(TABLE_EVENT_JOIN)
                        ->join(TABLE_USERS, TABLE_USERS . '.user_id = ' . TABLE_EVENT_JOIN . '.ej_user_id')
                        ->join(TABLE_EVENTS, TABLE_EVENTS . ".event_id = " . TABLE_EVENT_JOIN . ".ej_event_id")
                        ->where($whereCond)
                ;

                $result = $result->query()->fetchAll();



                $msg['message'] = $result[0]['user_first_name'] . ' ' . $result[0]['user_last_name'] . " has been rejected";
                $msg['accept'] = false;
                $msg['reject'] = true;


                $res = $this->commonModel->deleteRecord($whereCond, TABLE_EVENT_JOIN);


                //status code 4 - send notification to event joiner
                $this->addNotification($result[0]['user_id'], 4, $result[0]['event_id']);


                //status code 6 - send notification to host
                $this->addNotification($this->user_id, 6, $result[0]['event_id'], $result[0]['user_id']);
            }


            //prd($this->_getParam("redirect_uri"));
            $this->_redirect($this->_getParam("redirect_uri"));
            //exit(json_encode($msg));
        }

        function friendrequestAction()
        {
            $respond = $this->_getParam("respond");
            $request_id = $this->_getParam("rId");
            $this->commonModel = new Application_Model_Common;
            $msg = array();
            if ($respond == "accept")
            {
                $data['is_accepted'] = '1';
                $whereCond = "request_id = " . $request_id;
                $res = $this->commonModel->updateRecordData($data, $whereCond, TABLE_FRIEND_REQUESTS);

                if ($res)
                {
                    $where = "request_id =" . $request_id;
                    $result = $this->commonModel->getAllRecordFromInnerJoin('friend_requests', 'users', 'friend_requests.user_sent_from = users.user_id', $whereCond);
                    $msg['message'] = $result[0]['user_first_name'] . ' ' . $result[0]['user_last_name'] . " is now your friend";
                    $msg['accept'] = true;
                    $msg['reject'] = false;
                }
            }
            else
            {
                $whereCond = "request_id = " . $request_id;
                $result = $this->commonModel->getAllRecordFromInnerJoin('friend_requests', 'users', 'friend_requests.user_sent_from = users.user_id', $whereCond);
                $res = $this->commonModel->deleteRecord($whereCond, TABLE_FRIEND_REQUESTS);


                $msg['message'] = $result[0]['user_first_name'] . ' ' . $result[0]['user_last_name'] . " has been rejected";
                $msg['accept'] = false;
                $msg['reject'] = true;
            }

            exit(json_encode($msg));
        }

        //my review listing
        function getmyreviewAction()
        {

            $user_id = $this->_getParam('user_id');
            $page = $this->_getParam('page', 1);
            if (!$user_id)
            {
                echo json_encode(array("error" => true));
                die;
            }
            $cond = "user_rate_to=" . $user_id;
            $order = "rating_id desc";

            $userReviewData = $this->commonModel->select()->from(TABLE_RATING)->join(TABLE_USERS, TABLE_USERS . ".user_id = " . TABLE_RATING . ".user_rate_from")
                            ->setIntegrityCheck(false)
                            ->where($cond)->order($order)->limitPage($page, 10)->query()->fetchAll();
            //getAllRecordFromInnerJoin(array("ur" => TABLE_RATING), array("u" => TABLE_USERS), 'u.user_id = ur.user_rate_from', $cond, $order, $limit);

            foreach ($userReviewData as $rKey => $rValue)
            {
                $mustacheData['myreview'][$rKey]['rating'] = $rValue['rating'] . '/' . RATING_STARS_MAX;
                $mustacheData['myreview'][$rKey]['posted_date'] = date('F j Y', strtotime($rValue['rating_timestamp']));
                $mustacheData['myreview'][$rKey]['avatar'] = is_file(ROOT_PATH . "/" . MEMBER_IMAGE_PATH . "/" . $rValue['user_rate_to'] . ".jpg") ? $this->view->baseUrl(MEMBER_IMAGE_PATH . "/" . $rValue['user_rate_to'] . ".jpg") : $this->view->baseUrl(MEMBER_NO_IMAGE_FILE);
                $mustacheData['myreview'][$rKey]['profile_link'] = $this->view->baseUrl("profile/publicprofile/" . $rValue["user_id"]);
                $mustacheData['myreview'][$rKey]['comments'] = $rValue['comments'];
                $mustacheData['myreview'][$rKey]['reviewer_name'] = $rValue['user_first_name'] . " " . $rValue['user_last_name'];
            }
            echo json_encode($mustacheData);
        }

        //my rating listing
        function getmyrateAction()
        {

            $user_id = $this->_getParam('user_id');
            $page = $this->_getParam('page', 1);
            if (!$user_id)
            {
                echo json_encode(array("error" => true));
                die;
            }
            $cond = "user_rate_from =" . $user_id;
            $order = "rating_id desc";

            $userReviewData = $this->commonModel->select()->from(TABLE_RATING)->join(TABLE_USERS, TABLE_USERS . ".user_id = " . TABLE_RATING . ".user_rate_from")
                            ->setIntegrityCheck(false)
                            ->where($cond)->order($order)->limitPage($page, 10)->query()->fetchAll();
            //getAllRecordFromInnerJoin(array("ur" => TABLE_RATING), array("u" => TABLE_USERS), 'u.user_id = ur.user_rate_from', $cond, $order, $limit);

            foreach ($userReviewData as $rKey => $rValue)
            {
                $mustacheData['myreview'][$rKey]['avatar'] = is_file(ROOT_PATH . "/" . MEMBER_IMAGE_PATH . "/" . $rValue['user_rate_to'] . ".jpg") ? $this->view->baseUrl(MEMBER_IMAGE_PATH . "/" . $rValue['user_rate_to'] . ".jpg") : $this->view->baseUrl(MEMBER_NO_IMAGE_FILE);
                $mustacheData['myreview'][$rKey]['comments'] = $rValue['comments'];
            }
            echo json_encode($mustacheData);
        }

        function getpaginationAction()
        {
            $user_id = $this->_getParam('user_id');
            $page = $this->_getParam('page', 1);
            $context = $this->_getParam('context');

            switch ($context)
            {
                case 'rating': $cond = "user_rate_from=" . $user_id;
                    $order = "rating_id desc";
                    $limit = NULL;
                    $ratingAdapter = $this->commonModel->getAllRecordDetail(TABLE_RATING, $cond, $order, $limit, true);
                    $adapter = new Zend_Paginator_Adapter_DbSelect($ratingAdapter);
                    $paginator = new Zend_Paginator($adapter);
                    $paginator->setItemCountPerPage(10);
                    $paginator->setCurrentPageNumber($page);
                    $this->view->user_id = $user_id;
                    echo $this->view->paginationControl($paginator, 'Sliding', 'pagination/ajaxpagination.phtml', array('type_of_data' => 'rating'));
                    break;
                case 'review': $cond = "user_rate_to=" . $user_id;
                    $order = "rating_id desc";
                    $limit = NULL;
                    $userReviewAdapter = $this->commonModel->getAllRecordFromInnerJoin(array("ur" => TABLE_RATING), array("u" => TABLE_USERS), 'u.user_id = ur.user_rate_from', $cond, $order, NULL, true);
                    $adapter = new Zend_Paginator_Adapter_DbSelect($userReviewAdapter);
                    $paginator = new Zend_Paginator($adapter);
                    $paginator->setItemCountPerPage(10);
                    $paginator->setCurrentPageNumber($page);
                    $this->view->user_id = $user_id;
                    echo $this->view->paginationControl($paginator, 'Sliding', 'pagination/ajaxpagination.phtml', array('type_of_data' => 'review'));
                    break;

                case 'message_inbox': $msgAdapter = $this->messageModel->getUserMessages($this->user['user_id'], true, true);
                    $adapter = new Zend_Paginator_Adapter_DbSelect($msgAdapter);
                    $paginator = new Zend_Paginator($adapter);
                    $paginator->setItemCountPerPage(10);
                    $paginator->setCurrentPageNumber($page);
                    $this->view->user_id = $user_id;
                    echo $this->view->paginationControl($paginator, 'Sliding', 'pagination/ajaxpagination.phtml', array('type_of_data' => 'message_inbox'));
                    break;
                case 'message_outbox': $msgAdapter = $this->messageModel->getUserMessages($this->user['user_id'], false, true);
                    $adapter = new Zend_Paginator_Adapter_DbSelect($msgAdapter);
                    $paginator = new Zend_Paginator($adapter);
                    $paginator->setItemCountPerPage(10);
                    $paginator->setCurrentPageNumber($page);
                    $this->view->user_id = $user_id;
                    echo $this->view->paginationControl($paginator, 'Sliding', 'pagination/ajaxpagination.phtml', array('type_of_data' => 'message_outbox'));
                    break;
            }
        }

        public function addfriendAction()
        {
            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            if ($this->getRequest()->getParam("user_id") && !empty($y))
            {
                $group_id = $this->_getParam("group_id", 0);
                if ($group_id == "others")
                    $group_id = "0";
                $enc_user_id = $this->getParam("user_id");
                $request_send_from = $x->read()->user_id;
                $request_send_to = getEncryptedString($enc_user_id, "decode");
                $from_ipaddress = $_SERVER["REMOTE_ADDR"];

                $model = new Application_Model_Common();
                $isExistWhere = "user_sent_from=$request_send_from AND user_sent_to = $request_send_to AND group_id=$group_id";
                $is_exist = $model->is_exists(TABLE_FRIEND_REQUESTS, $isExistWhere);
                if (empty($is_exist))
                {
                    //add request
                    $data_array = array(
                        "user_sent_from" => $request_send_from,
                        "user_sent_to" => $request_send_to,
                        "from_ipaddress" => $from_ipaddress,
                        "group_id" => $group_id
                    );


                    try
                    {
                        //$model->deleteRecord('user_sent_from = '.$request_send_from.' and user_sent_to = '.$request_send_to, TABLE_FRIEND_REQUESTS);
                    }
                    catch (Exception $e)
                    {
                        
                    }

                    $model->insertRecordData($data_array, TABLE_FRIEND_REQUESTS);

                    $msg['message'] = 'Friend successfully added';
                    $msg['error'] = false;
                    $msg['success'] = true;
                }
                else
                {
                    $msg['message'] = 'Friend already exists in the group';
                    $msg['error'] = TRUE;
                    $msg['success'] = FALSE;
                }
            }
            else
            {

                $msg['message'] = 'Oops! some error occurred';
                $msg['error'] = true;
                $msg['success'] = false;
                $msg['reason'] = 'session time out';
            }
            exit(json_encode($msg));
        }

        function getsubcategoriesAction()
        {
            $category_id = $this->_getParam("catId");
            $msg = array();
            if (!$category_id)
            {
                $msg['message'] = 'Oops! some error occurred';
                $msg['error'] = true;
                $msg['success'] = false;
                $msg['reason'] = 'category id not found';
                exit(json_encode($msg));
            }
            //$category_id = getEncryptedString($category_id,'decode');
            $subcatArr = $this->commonModel->getAllRecordDetail('subcategory', 'category_id = ' . $category_id);
            $msg['data'] = $subcatArr;
            $msg['message'] = '';
            $msg['success'] = true;
            $msg['error'] = false;
            exit(json_encode($msg));
        }

        function getpopupAction()
        {
            $user_id = $this->_getParam('user_id');
            $this->view->getHelper('Profile')->init($user_id);
        }

        function eventAction()
        {
            $commonModel = new Application_Model_Common;

            $event_id = $this->_getParam("id");
            $data = $this->getRequest()->getPost();

            $subcat_id_arr = $commonModel->getdata(TABLE_SUB_CATEGORY, "subcategory_name = '" . $data["event_subcat_id"] . "'");

            $subcat_id = $subcat_id_arr["subcategory_id"];

            if (empty($subcat_id_arr["subcategory_id"]))
            {
                $data_arr['subcategory_name'] = $data['event_subcat_id'];
                $data_arr['category_id'] = $data['event_cat_id'];
                $commonModel->insertRecordData($data_arr, TABLE_SUB_CATEGORY);
                $subcat_id = $commonModel->getLastInsertId(TABLE_SUB_CATEGORY);
            }
            else
            {
                $subcat_id = $subcat_id_arr["subcategory_id"];
            }

            $data["event_subcat_id"] = $subcat_id;

//            $country_id_arr = $commonModel->getdata(TABLE_COUNTRY, "country_name = '" . $data["event_country"] . "'");
//            $data["event_country"] = $country_id_arr["country_id"];

            $data['event_date_type'] = $data['rdate'];
            unset($data['rdate']);

            if ($data['event_date_type'] == 'recurring')
                $date_array_json = array(
                    "day" => $data["date"],
                    "month" => $data["month"],
                    "year" => $data["year"]
                );
            else
                $date_array_json = array(
                    "day" => $data["sdate"],
                    "month" => $data["smonth"],
                    "year" => $data["syear"]
                );

            unset($data["date"], $data["month"], $data["year"], $data['sdate'], $data['smonth'], $data['syear']);
            $data['event_date'] = json_encode($date_array_json);
            $data["event_time"] = $data["hour"] . ":" . $data["minute"] . " " . $data["ampm"];

            $edate_array_json = array(
                "day" => $data["edate"],
                "month" => $data["emonth"],
                "year" => $data["eyear"]
            );

            $data['event_end_date'] = json_encode($edate_array_json);

            unset($data['hour'], $data['minute'], $data['ampm'], $data['agree'], $data["edate"], $data["emonth"], $data["eyear"]);


            @$event_image_file = $_FILES['event_image'];
            unset($data['event_image']);


            $data["event_created_by"] = $this->user_id;
            if ($event_id)
            {
                $commonModel->updateRecordData($data, 'event_id = ' . $event_id, TABLE_EVENTS);
                //send notification to users that an event has been modified - status 9
                $this->addNotificationToAllUsers($event_id, 9);
            }
            else
            {
                if ($data['event_celebrity_event'] == "1")
                    $data["event_active"] = "0";
//                prd($data);

                $event_id = $commonModel->insertRecordData($data, TABLE_EVENTS);
            }



            $dir_name = getEncryptedString($event_id);
            //transfering files from temp to event
            if (!is_dir("resources/event-pics/" . $dir_name))
                mkdir("resources/event-pics/" . $dir_name);

            foreach (glob("resources/temp/" . $this->user_id . "/*") as $filename)
            {
                $file = explode("/", $filename);
                $file = end($file);
                copy($filename, "resources/event-pics/" . $dir_name . "/" . $file);
                unlink($filename);
            }


            $msg['success'] = true;
            $msg['message'] = 'Event successfully created';
            $msg['event_id'] = $event_id;
            $msg['encrypted_event_id'] = getEncryptedString($event_id);
            echo json_encode($msg);
        }

        function fileuploadAction()
        {
            $event_id = $this->_getParam('id');
            $event_image = $_FILES['event_image'];
            if (!@is_dir(EVENT_IMAGE_PATH . "/" . getEncryptedString($event_id)))
                @mkdir(EVENT_IMAGE_PATH . "/" . getEncryptedString($event_id));


            foreach ($event_image_file as $key => $value)
            {
                move_uploaded_file($_FILES['tmp_name'], EVENT_IMAGE_PATH . "/" . getEncryptedString($event_id) . "/" . getEncryptedString($event_id) . "-" . $key . ".jpg");
            }
        }

        function checkloginAction()
        {

            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            $msg = array();

            if (!empty($y))
            {
                $msg['success'] = true;
                $msg['error'] = false;
                $msg['reason'] = "User Logged in";
            }
            else
            {
                $msg['success'] = false;
                $msg['error'] = true;
                $msg['reason'] = "User not logged";
            }

            exit(json_encode($msg));
        }

        function eventjoinAction()
        {
            $approve = $this->_getParam('approve');
            $user_id = $this->_getParam('user_id');
            $event_id = $this->_getParam('event_id');
//            prd("hello");
            $msg = array();
            if ($event_id && $user_id)
            {
                $commonModel = new Application_Model_Common;
                if ($approve == 'true')
                {
                    $data = array();
                    $data['ej_event_id'] = $event_id;
                    $data['ej_user_id'] = $user_id;
                    $data['ej_is_accepted'] = '1';
                    $data['ej_is_invited'] = '0';

                    $commonModel->deleteRecord('ej_user_id = ' . $user_id . ' and ej_event_id = ' . $event_id, TABLE_EVENT_JOIN);
//                    $commonModel->updateRecordData($data, 'ej_user_id = ' . $user_id . ' and ej_event_id = ' . $event_id, TABLE_EVENT_JOIN);
                    $commonModel->insertRecordData($data, TABLE_EVENT_JOIN);

                    //send notification to Host : status - 5
                    $this->addNotification($this->user_id, 5, $event_id, $user_id);

                    //send notification to user : status - 3
                    $this->addNotification($user_id, 3, $event_id);
                }
                else
                {
                    $data = array();
                    $commonModel->deleteRecord('ej_user_id = ' . $user_id . ' and ej_event_id = ' . $event_id, TABLE_EVENT_JOIN);

                    $this->addNotification($user_id, 2);
                }
                $msg['success'] = true;
                $msg['error'] = false;
                $msg['message'] = 'Your action has been performed successfully';
            }
            $msg['success'] = false;
            $msg['error'] = true;
            $msg['message'] = 'Oops! Some error occurred';

            exit(json_encode($msg));
        }

        public function getallsubcategoriescsvAction()
        {
//            $cat_id = trim($this->getParam("cat_id"));
            $where = "1";
            if ($this->_getParam("cat_id"))
            {
                $cat_id = $this->_getParam("cat_id");
                $where = "category_id = $cat_id";
            }

            $model = new Application_Model_Common();
            $records = $model->getAllRecordDetail(TABLE_SUB_CATEGORY, $where, "subcategory_name");

            $new_array = array();
            foreach ($records as $key => $value)
            {
                $new_array[] = $value["subcategory_name"];
            }

            echo json_encode($new_array);
//            echo implode(", ", $new_array);
            die;
        }

        public function getallcitiescsvAction()
        {
            $model = new Application_Model_Common();

            $records = $model->getAllRecordDetail(TABLE_CITY, "1", "city_name");

            $new_array = array();
            foreach ($records as $key => $value)
            {
                $new_array[] = $value["city_name"];
            }

            echo json_encode($new_array);
            die;
        }

        public function getallcountriescsvAction()
        {
            $model = new Application_Model_Common();

            $records = $model->getAllRecordDetail(TABLE_COUNTRY, "1", "country_name");

            $new_array = array();
            foreach ($records as $key => $value)
            {
                $new_array[] = $value["country_name"];
            }

            echo json_encode($new_array);
            die;
        }

        public function addNotification($userId, $statusCode, $event_id, $joiner_id = false)
        {
            $data_array['notification_user_id'] = $userId;
            $data_array['notification_code'] = $statusCode;
            $data_array['notification_event_id'] = $event_id;
            if ($joiner_id)
                $data_array['notification_event_joiner'] = $joiner_id;
//            prd($data_array);
            $result = $this->commonModel->insertRecordData($data_array, TABLE_NOTIFICATION);
        }

        function addNotificationToAllUsers($event_id, $statusCode)
        {

            $usersData = $this->commonModel->getAllRecordDetail(TABLE_EVENT_JOIN, "ej_event_id = " . $event_id . " and ej_is_accepted = '1'");



            $data_array['notification_code'] = $statusCode;
            $data_array['notification_event_id'] = $event_id;

            foreach ($usersData as $value)
            {
                $data_array['notification_user_id'] = $value['ej_user_id'];
                $result = $this->commonModel->insertRecordData($data_array, TABLE_NOTIFICATION);
            }
        }

        function doajaxfileuploadAction()
        {

            //check if edit or save
            $event_id = $this->_getParam("event_id");
            $cevent_id = getEncryptedString($event_id);

            if (!empty($event_id))
            {
                $total_count = count(glob("resources/event-pics/" . $cevent_id . "/*"));
            }
            else
            {
                $total_count = count(glob("resources/temp/" . $_REQUEST['id'] . "/*"));
            }

            $fileElementName = 'event_image';
            //prd($_FILES);
            if (count($_FILES[$fileElementName]['name']) + $total_count > 4)
            {
                $msg['error'] = "Maximum files uploading limit exceeded";
                $msg['reason'] = count($_FILES[$fileElementName]);
                exit(json_encode($msg));
            }

            foreach ($_FILES[$fileElementName]['name'] as $key => $files):
                if (!empty($_FILES[$fileElementName]['error'][$key]))
                {
                    switch ($_FILES[$fileElementName]['error'][$key])
                    {

                        case '1':
                            $msg['error'] = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                            break;
                        case '2':
                            $msg['error'] = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                            break;
                        case '3':
                            $msg['error'] = 'The uploaded file was only partially uploaded';
                            break;
                        case '4':
                            $msg['error'] = 'No file was uploaded.';
                            break;

                        case '6':
                            $msg['error'] = 'Missing a temporary folder';
                            break;
                        case '7':
                            $msg['error'] = 'Failed to write file to disk';
                            break;
                        case '8':
                            $msg['error'] = 'File upload stopped by extension';
                            break;
                        case '999':
                        default:
                            $msg['error'] = 'No error code avaiable';
                    }
                }
                elseif (empty($_FILES[$fileElementName]['tmp_name'][$key]) || $_FILES[$fileElementName]['tmp_name'][$key] == 'none')
                {
                    $msg['error'] = 'No file was uploaded..';
                }
                else
                {
                    $allowed_extnsn = explode(",", strtolower(IMAGE_EXTNSN));


                    //prd($_FILES);
                    $extnsn = explode(".", strtolower($_FILES[$fileElementName]['name'][$key]));



                    if (in_array($extnsn[count($extnsn) - 1], $allowed_extnsn))
                    {
                        $newfilename = $_REQUEST['id'] . "." . $extnsn[count($extnsn) - 2] . time() . "." . $extnsn[count($extnsn) - 1];

                        $img = new Application_Plugin_SimpleImage();
                        $img->load($_FILES[$fileElementName]['tmp_name'][$key]);
                        $width = 500;
                        $height = NULL;

                        if ($height == NULL || empty($height))
                        {
                            $img->resizeToWidth($width);
                        }
                        else
                        {
                            $img->resize($width, $height);
                        }
                        $img->save("resources/temp/" . $_REQUEST['id'] . "/" . $newfilename);
                        {
                            //$files = glob(SITE_ROOT . "ankit_ups/*");
                            //$msg['number_of_files'] = 1;
                            $msg['filename'][] = $newfilename;
                            $msg['success'] = 1;
                            $msg['error'] = false;
                            //$msg['name'] = $newfilename;
                        }
                    }
                    else
                    {
                        $msg['error'] = $msg['extnsn'] = "Image Extension is wrong";
                    }
                }
            endforeach;

            echo json_encode($msg);
        }

        public function deleteeventmemberAction()
        {
            $ej_id = $this->_getParam("ej_id");

            $msg['success'] = false;
            $msg['error'] = true;
            $msg['message'] = 'Oops! Some error occurred';

            if ($ej_id)
            {
                $commonModel = new Application_Model_Common;

                $data = array();
                $record = $commonModel->getAllRecordFromInnerJoin(TABLE_EVENT_JOIN, TABLE_USERS, TABLE_USERS . ".user_id = " . TABLE_EVENT_JOIN . ".ej_user_id", "ej_id=" . $ej_id);


                $commonModel->deleteRecord("ej_id=" . $ej_id, TABLE_EVENT_JOIN);

                //send notification to user - status 7
                $this->addNotification($record[0]['user_id'], 7, $record[0]['ej_event_id']);

                //send notification to host - status 8
                $this->addNotification($this->user_id, 8, $record[0]['ej_event_id'], $record[0]['ej_user_id']);


                $msg['success'] = true;
                $msg['error'] = false;
                $msg['message'] = 'Your action has been performed successfully';
            }


            exit(json_encode($msg));
        }

        function notificationcountAction()
        {

            $type = $this->_getParam('type');
            $data['success'] = false;
            $data['error'] = true;

            if (!empty($this->user_id))
            {

                if ($type == 'notification')
                {
                    $data_update['notification_count'] = 'hidden';
                    //prd($this->commonModel->getAllRecordDetail(TABLE_NOTIFICATION,"notification_user_id = '".$this->user_id."'"));
                    $ret = $this->commonModel->updateRecordData($data_update, "notification_count='visible' and notification_user_id = '" . $this->user_id . "'", TABLE_NOTIFICATION);
                    //prd($ret);
                }
                elseif ($type == 'message')
                {
                    $data_update['message_count'] = 'hidden';
                    $ret = $this->commonModel->updateRecordData($data_update, "message_count='visible' and message_to = '" . $this->user_id . "'", TABLE_MESSAGES);
                }
                if ($ret)
                {
                    $data['message'] = 'successfully removed count';
                    $data['success'] = true;
                    $data['error'] = false;
                    echo (json_encode($data));
                    die;
                }

                echo json_decode($data);
            }


            echo json_encode($data);
            die;
        }

        public function getsubcategoriesforsearchAction()
        {
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $category_id = $arr["cat_id"];
                $model = new Application_Model_Common();
                $records = $model->getAllRecordDetail(TABLE_SUB_CATEGORY, "category_id=$category_id", "subcategory_name");

                $str = "";
                foreach ($records as $key => $value)
                {
                    $str .= '<div class="item search-box-categories" rel="' . $value["subcategory_id"] . '">
                                    <img class="fl thumb" src="' . IMAGES_PATH . '/thumb1.1.jpg" alt="thumb" />
                                    <div class="content">
                                        <p><a href="' . $value["subcategory_id"] . '" rel="' . $value["subcategory_id"] . '" class="name search-box-categories subcats">' . $value["subcategory_name"] . '</a></p>
                                        <!--<p class="desc">' . $value["subcategory_name"] . '</p>-->
                                    </div>
                                    <div class="cf"></div>
                                </div>';
                }

                $str .= '<input type="hidden" name="subcategory_id" id="subcat_id" value=""/>';

                echo $str;
            }
            die;
        }

        public function getvideopreviewAction()
        {
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $video_url = $arr["video_url"];
                $video_serviceName = getVideoServiceName($video_url);
                $video_id = $video_serviceName["video_id"];
                $video_service = $video_serviceName["video_service"];

                $iframe_url = getVideoEmbedUrl($video_id, $video_service);
                echo "<iframe src= '" . $iframe_url . "' width='333' height='204'></iframe>";
            }
            die;
        }

        public function eventinviteAction()
        {
            if ($this->getParam("event_id") && $this->getParam("user_id"))
            {
                $event_id = getEncryptedString($this->getParam("event_id"), "decode");
//                $user_id = getEncryptedString($this->getParam("user_id"), "decode");
                $user_id = $this->getParam("user_id");
                $model = new Application_Model_Common();

                $is_exist = $model->is_exists(TABLE_EVENT_JOIN, "ej_user_id=$user_id AND ej_event_id=$event_id AND ej_is_invited = '1'");

                if (empty($is_exist))
                {
                    $data = array();
                    $data['ej_user_id'] = $user_id;
                    $data['ej_event_id'] = $event_id;
                    $data['ej_is_accepted'] = '1';
                    $data['from_ipaddress'] = $_SERVER["REMOTE_ADDR"];
                    $data['ej_is_invited'] = '1';
//                prd($data);
                    $model->insertRecordData($data, TABLE_EVENT_JOIN);

                    $this->addNotification($user_id, 11, $event_id, $this->user_id);
                }
            }
            die;
        }

        public function rateuserAction()
        {
            if ($this->getParam("user_id") && isset($this->user_id) && $this->getRequest()->isPost())
            {
                $user_id = $this->getParam("user_id");
                $model = new Application_Model_Common();
                $arr = $this->getRequest()->getPost();

                $user_rate_from = $this->user_id;
                $user_rate_to = $user_id;
                $whereCond = "user_rate_from=$user_rate_from AND user_rate_to=$user_rate_to";

                $is_exists = $model->is_exists(TABLE_RATING, $whereCond);

                if (!empty($is_exists))
                {
                    $model->deleteRecord($whereCond, TABLE_RATING);
                }

                $data_array = array(
                    "user_rate_from" => $user_rate_from,
                    "user_rate_to" => $user_rate_to,
                    "from_ipaddress" => $_SERVER["REMOTE_ADDR"],
                    "rating" => $arr["rating"]
                );
                $model->insertRecordData($data_array, TABLE_RATING);
                echo '1';
            }
            die;
        }

        public function removesharedeventAction()
        {
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $model = new Application_Model_Common();
                $event_id = getEncryptedString($arr["event_id"], "decode");
                $user_id = $arr["user_id"];

                $whereCond = "ej_event_id = $event_id AND ej_user_id = $user_id AND ej_is_invited = '1'";
                $model->deleteRecord($whereCond, TABLE_EVENT_JOIN);
            }
            die;
        }

    }

    